var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var isRefresh = false;
var wt_type = $("#wt_type").val();
var shop_type = $("#shop_type").val();
var api = frameElement.api, W = api.opener;
var callback = api.data.callback,oper = api.data.oper;
var queryurl = config.BASEPATH+'shop/want/temp_list/'+wt_type;
var querysumurl = config.BASEPATH+'shop/want/temp_sum/'+wt_type;
var querysizeurl = config.BASEPATH+'shop/want/temp_size/'+wt_type;
var querysizetitleurl = config.BASEPATH+'shop/want/temp_size_title/'+wt_type;

var needListRefresh = false;//列表模式
var needSizeRefresh = false;//尺码模式
var needSumRefresh = false;//汇总模式
var _height = $(parent).height()-353,_width = $(parent).width()-2;
var showMode = {
	display:function(mode){
		var ids = $("#grid").getDataIDs();
		if(ids == undefined || null == ids || ids.length == 0){
			if(mode != 0){
				Public.tips({type: 1, content : "未添加数据，不能切换模式"});
				return;
			}
		}
		$("#CurrentMode").val(mode);
		$("a[name='mode-btn']").removeClass("on");
		$("#list-grid").hide();
		$("#size-grid").hide();
		$("#sum-grid").hide();
		if(mode == 0){
			$("#listBtn").addClass("on");
			$("#list-grid").show();
			showMode.refreshList();
		}else if(mode == 1){
			$("#sizeBtn").addClass("on");
			$("#size-grid").show();
			showMode.refreshSize();
		}else if(mode == 2){
			$("#sumBtn").addClass("on");
			$("#sum-grid").show();
			showMode.refreshSum();
		}
	},
	refreshList:function(){//列表模式刷新数据
		if(!needListRefresh){
    		return;
    	}
    	THISPAGE.reloadGridData();
    	needListRefresh = false;
	},
	refreshSum:function(){
		if(!needSumRefresh){
			return;
		}
		$('#sumGrid').GridUnload();
		THISPAGE.addEvent();
		THISPAGE.initSumGrid();
		needSumRefresh = false;
	},
	refreshSize:function(){
		if(!needSizeRefresh){
			return;
		}
		$.ajax({
			type:"POST",
			url:querysizetitleurl,
			cache:false,
			dataType:"json",
            success: function (data) {
            	if(undefined != data && data.stat == 200){
                    var titles = data.data.titles;
                    var sizeCodeMap = data.data.sizeCodeMap;
                    $('#sizeGrid').GridUnload();
                    THISPAGE.initSizeGroupGrid(titles, sizeCodeMap);
                    THISPAGE.addEvent();
                    needSizeRefresh = false;
				}else{
					Public.tips({type: 1, content : data.message});
				}
            }
        });
	},
	refresh:function(){
		var currentMode = $("#CurrentMode").val();
    	if(currentMode == '0'){//列表模式
    		needListRefresh = true;
    		showMode.refreshList();
        	needSizeRefresh = true;
        	needSumRefresh = true;
    	}else if(currentMode == '1'){//尺码模式
    		needSizeRefresh = true;
    		showMode.refreshSize();
    		needListRefresh = true;
        	needSumRefresh = true;
    	}else if(currentMode == '2'){//汇总模式
    		needSumRefresh = true;
    		showMode.refreshSum();
    		needListRefresh = true;
        	needSizeRefresh = true;
    	}
	}
};

var Choose = {
	copy:function(){
		commonDia = $.dialog({
			title : '复制单据',
			content : 'url:'+config.BASEPATH+'shop/want/to_list_copy_dialog',
			data : {},
			width : 1080,
			height : 440,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				Choose.doCopy(selected.detailIds);
			},
			close:function(){
			},
			cancel:true
		});
	},
	doCopy:function(detailIds){
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'shop/want/temp_copy/'+wt_type,
			data:{ids:detailIds.join(",")},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					Public.tips({type: 3, content : "复制成功！"});
					showMode.refresh();
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
	},
	doImport:function(){
		isRefresh = false;
		var wt_shop_code = $.trim($("#wt_shop_code").val());
		if (wt_shop_code == '') {
			Public.tips({type: 2, content : "请先选择要货门店！"});
	        return;
	    }
		$.dialog({ 
		   	id:'import',
		   	title:'盘点机导入',
		   	content:'url:'+config.BASEPATH+'common/to_barcodeimport',
		   	data : {postData:{sp_code:wt_shop_code},
					saveSuccUrl:config.BASEPATH+"shop/want/temp_import/"+wt_type
		   		},
		   	max: false,
		   	min: false,
		   	lock:true,
		   	width:700,
		   	height:470,
		   	fixed:false,
		   	drag: true,
		   	resize:false,
		   	lock:true,
		   	close: function () {
		   		if(isRefresh){
		   			showMode.refresh();
		   		}
			}
		});
	},
	selectProduct:function(){
		var wt_shop_code = $.trim($("#wt_shop_code").val());
		var wt_outdp_code = $.trim($("#wt_outdp_code").val());
		var wt_indp_code = $.trim($("#wt_indp_code").val());
		var dp_code = '';
		if (wt_shop_code == '') {
			Public.tips({type: 2, content : "请先选择要货门店！"});
	        return;
	    }
		if((wt_type == 0 && (shop_type == 1 || shop_type == 2)) || (wt_type == 1 && shop_type == 3 )){
			if (wt_outdp_code == '') {
				Public.tips({type: 2, content : "请先选择仓库！"});
		        return;
		    }
			dp_code = wt_outdp_code;
		}else if((wt_type == 1 && (shop_type == 1 || shop_type == 2)) || (wt_type == 0 && shop_type == 3)){
			if (wt_indp_code == '') {
				Public.tips({type: 2, content : "请先选择仓库！"});
		        return;
		    }
			dp_code = wt_indp_code;
		}else{
			Public.tips({type: 2, content : "系统异常！"});
	        return;
		}
		$.dialog({
			title : '商品录入',
			content : 'url:'+config.BASEPATH+'shop/want/to_select_product/'+wt_type,
			data : {dp_code:dp_code,sp_code:wt_shop_code,searchContent:$.trim($("#pd_no").val())},
			width : 1080,
			height : 440,
			max : false,
			min : false,
			cache : false,
			lock: true,
			close:function(){
				showMode.refresh();
			}
		});
	},
	barCode:function(){
		var CurrentMode = $("#CurrentMode").val();
		if(CurrentMode == 1){//若是尺码模式调整到列表模式
			showMode.display(0);
		}
		var barcode = $.trim($("#barcode").val());
		var barcode_amount = $.trim($("#barcode_amount").val());
		if(barcode == ""){
			return;
		}
		if (barcode_amount == "" || isNaN(barcode_amount)) {
			Public.tips({type: 2, content : '请正确输入数量!'});
	        $('#barcode_amount').select();
	        return;
	    }
		var wt_shop_code = $.trim($("#wt_shop_code").val());
		if (wt_shop_code == '') {
			Public.tips({type: 2, content : "请先选择要货门店！"});
	        return;
	    }
		var params = "";
		params += "barcode="+barcode;
		params += "&amount="+barcode_amount;
		params += "&sp_code="+wt_shop_code;
		$.ajax({
			type:"POST",
			url:config.BASEPATH+"shop/want/temp_save_bybarcode/"+wt_type,
			data:params,
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					if(data.data.result == 3){//条码不存在
						Choose.barcodeNotExist(barcode);
						return;
					}
					needSizeRefresh = true;
					$("#barcode").val("");
					var temp = data.data.temp;
					//列表模式
					if(data.data.result == 1){//update
						var rowData = $("#grid").jqGrid("getRowData", temp.wtl_id);
						rowData.wtl_applyamount = temp.wtl_applyamount;
						rowData.wtl_unitmoney = rowData.wtl_applyamount * rowData.wtl_unitprice;
						rowData.wtl_costmoney = rowData.wtl_applyamount * rowData.wtl_costprice;
						$("#grid").delRowData(temp.wtl_id);
						$("#grid").addRowData(temp.wtl_id, rowData, 'first');
						THISPAGE.gridTotal();
					}else if(data.data.result == 2){//add
						$("#grid").addRowData(temp.wtl_id, temp, 'first');
						THISPAGE.gridTotal();
					}
					//汇总模式
			    	var ids = $("#sumGrid").jqGrid('getDataIDs');
	            	var oldSumRowData = null;
	            	var sum_id = null;
					for(var i=0;i < ids.length;i++){
						var sumRowData = $("#sumGrid").jqGrid("getRowData", ids[i]);
						if(sumRowData.pd_code == temp.pd_code){
							oldSumRowData = sumRowData;
							sum_id = ids[i];
							break;
						}
					}
					if(oldSumRowData != null){
						oldSumRowData.wtl_applyamount = parseInt(oldSumRowData.wtl_applyamount) + parseInt(barcode_amount);
						oldSumRowData.wtl_unitmoney = oldSumRowData.wtl_applyamount * oldSumRowData.wtl_unitprice;
						oldSumRowData.wtl_costmoney = oldSumRowData.wtl_applyamount * oldSumRowData.wtl_costprice;
						$("#sumGrid").jqGrid('setRowData', sum_id, oldSumRowData);
						THISPAGE.sumGridTotal();
					}else{
						$("#sumGrid").addRowData(temp.wtl_id, temp, 'first');
						THISPAGE.sumGridTotal();
					}
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
	},
	barcodeNotExist:function(barcode){
		$("#barcode").val("无此商品").select();
		var BarCodeCheckNotPass = document.getElementById("BarCodeCheckNotPass");
		if(BarCodeCheckNotPass.style.display == 'none'){
			BarCodeCheckNotPass.style.display = '';
			
			var barCodeDiv=$("#BarCodeCheckNotPass");
			var barCodeDivTop=$("#barcode_amount").offset().top
				,barCodeDivLeft=$("#barcode_amount").offset().left;
			barCodeDiv.css(
			{
				"top":barCodeDivTop-150
				,"left":barCodeDivLeft+30
			}
			);
		}
		var CheckNotPassText = document.getElementById("CheckNotPassText");
		if($("#CheckNotPassTextShow").val().indexOf(barcode+";") > -1){
			return;
		}
		CheckNotPassText.innerHTML = CheckNotPassText.innerHTML + "<p>" + barcode + "</p>";
		$("#CheckNotPassTextShow").val($("#CheckNotPassTextShow").val()+barcode+";");
	}
};

var Utils = {
	doQueryShop : function(){
		commonDia = $.dialog({
			title : '选择要货门店',
			content : 'url:'+config.BASEPATH+'base/shop/list_dialog_bymodule',
			data : {multiselect:false,module:'want'},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#wt_shop_code").val(selected.sp_code);
				$("#shop_name").val(selected.sp_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#wt_shop_code").val(selected.sp_code);
					$("#shop_name").val(selected.sp_name);
				}
			},
			cancel:true
		});
	},
	doQueryDepot : function(code,name){
		commonDia = $.dialog({
			title : '选择仓库',
			content : 'url:'+config.BASEPATH+'base/depot/to_list_dialog_bymodule',
			data : {multiselect:false,module:'want'},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				if(selected){
					$("#"+code).val(selected.dp_code);
					$("#"+name).val(selected.dp_name);
				}
			},
			cancel:true
		});
	},
	doQueryEmp : function(){
		commonDia = $.dialog({
			title : '选择经办人',
			content : 'url:'+config.BASEPATH+'base/emp/to_list_dialog',
			data : {multiselect:false},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#wt_manager").val(selected.em_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#wt_manager").val(selected.em_name);
				}
			},
			cancel:true
		});
	},
	doQueryUser : function(){
		commonDia = $.dialog({
			title : '选择审核人',
			content : 'url:'+config.BASEPATH+'sys/user/to_list_dialog',
			data : {multiselect:false},
			width : 550,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#wt_ar_usid").val(selected.us_id);
				$("#ar_usname").val(selected.us_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#wt_ar_usid").val(selected.us_id);
					$("#ar_usname").val(selected.us_name);
				}
			},
			cancel:true
		});
	},
	doQueryStream : function(){
		commonDia = $.dialog({
			title : '选择物流公司',
			content : 'url:'+config.BASEPATH+'base/stream/to_list_dialog',
			data : {multiselect:false},
			width : 350,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#wt_stream_code").val(selected.wt_code);
				$("#stream_name").val(selected.wt_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#wt_stream_code").val(selected.wt_code);
					$("#stream_name").val(selected.wt_name);
				}
			},
			cancel:true
		});
	}
};

var handle = {
	temp_updateRemarkById:function(rowid,remark){
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'shop/want/temp_updateRemarkById',
			data:{wtl_id:rowid,wtl_remark:Public.encodeURI(remark)},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					var rowData = $("#grid").jqGrid("getRowData", rowid);
					var ids = $("#sumGrid").jqGrid('getDataIDs');
					for(var i=0;i < ids.length;i++){
						var row = $("#sumGrid").jqGrid("getRowData", ids[i]);
						if(row.wtl_pd_code == rowData.wtl_pd_code){
							$("#sumGrid").jqGrid('setRowData',ids[i],{wtl_remark:remark});
						}
					}
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
    },
    temp_updateRemarkByPdCode:function(pd_code,remark){
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'shop/want/temp_updateRemarkByPdCode/'+wt_type,
			data:{wtl_pd_code:pd_code,wtl_remark:Public.encodeURI(remark)},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					var ids = $("#grid").jqGrid('getDataIDs');
					for(var i=0;i < ids.length;i++){
						var row = $("#grid").jqGrid("getRowData", ids[i]);
						if(row.wtl_pd_code == pd_code){
							$("#grid").jqGrid('setRowData',ids[i],{wtl_remark:remark});
						}
					}
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
    },
	temp_updateAmount:function(rowid,amount){
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'shop/want/temp_updateAmount',
			data:{wtl_id:rowid,wtl_applyamount:amount},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					needSizeRefresh = true;
					needSumRefresh = true;
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
    },
    temp_updatePrice:function(pd_code,unitPrice){
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'shop/want/temp_updatePrice/'+wt_type,
			data:{wtl_pd_code:pd_code,wtl_unitprice:unitPrice},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					showMode.refresh();
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
    },
	temp_update : function(id,type){
		var wt_shop_code = $.trim($("#wt_shop_code").val());
		var wt_outdp_code = $.trim($("#wt_outdp_code").val());
		var wt_indp_code = $.trim($("#wt_indp_code").val());
		var dp_code = '';
		if (wt_shop_code == '') {
			Public.tips({type: 2, content : "请先选择要货门店！"});
	        return;
	    }
		if((wt_type == 0 && (shop_type == 1 || shop_type == 2)) || (wt_type == 1 && shop_type == 3 )){
			if (wt_outdp_code == '') {
				Public.tips({type: 2, content : "请先选择仓库！"});
		        return;
		    }
			dp_code = wt_outdp_code;
		}else if((wt_type == 1 && (shop_type == 1 || shop_type == 2)) || (wt_type == 0 && shop_type == 3)){
			if (wt_indp_code == '') {
				Public.tips({type: 2, content : "请先选择仓库！"});
		        return;
		    }
			dp_code = wt_outdp_code;
		}else{
			Public.tips({type: 2, content : "系统异常！"});
	        return;
		}
		var params = {};
 		var rowData;
 		if(type == '0'){
 			rowData = $("#grid").jqGrid("getRowData", id);
 			params.pd_code = rowData.wtl_pd_code;
 		}else if(type == '1'){
			rowData = $("#sizeGrid").jqGrid("getRowData", id);
			params.pd_code = rowData.pd_code;
		}else if(type == '2'){
			rowData = $("#sumGrid").jqGrid("getRowData", id);
			params.pd_code = rowData.wtl_pd_code;
		}
 		params.sp_code = wt_shop_code;
 		params.dp_code = dp_code;
		$.dialog({
			title : '修改商品',
			content : 'url:'+config.BASEPATH+'shop/want/to_temp_update/'+wt_type,
			data : params,
			width : 850,
			height : 440,
			max : false,
			min : false,
			cache : false,
			lock: true,
			close:function(){
				showMode.refresh();
			}
		});
	},
	temp_del: function(rowId){//删除
		if(rowId != null && rowId != ''){
			var rowData = $("#grid").jqGrid("getRowData", rowId);
		 	$.dialog.confirm('数据删除后无法恢复，确定要清除吗？', function(){
				$.ajax({
					type:"POST",
					url:config.BASEPATH+'shop/want/temp_del',
					data:{"wtl_id":rowId},
					cache:false,
					dataType:"json",
					success:function(data){
						if(undefined != data && data.stat == 200){
							Public.tips({type: 3, content : '删除成功!'});
							$('#grid').jqGrid('delRowData', rowId);
							THISPAGE.gridTotal();
							needSizeRefresh = true;
							needSumRefresh = true;
						}else{
							Public.tips({type: 1, content : data.message});
						}
					}
				});
			});
	   }else{
		   Public.tips({type: 1, content : '请选择数据!'});
	   }	
    },
    temp_delByPiCode: function(rowId,type){//删除
		if(rowId != null && rowId != ''){
		 	$.dialog.confirm('数据删除后无法恢复，确定要清除吗？', function(){
		 		var params = {};
		 		var rowData;
	    		if(type == '1'){
	    			rowData = $("#sizeGrid").jqGrid("getRowData", rowId);
	    			params.pd_code = rowData.pd_code;
	    			params.cr_code = rowData.cr_code;
	    			params.br_code = rowData.br_code;
	    		}else if(type == '2'){
	    			rowData = $("#sumGrid").jqGrid("getRowData", rowId);
	    			params.pd_code = rowData.wtl_pd_code;
	    		}
				$.ajax({
					type:"POST",
					url:config.BASEPATH+'shop/want/temp_delByPiCode/'+wt_type,
					data:params,
					cache:false,
					dataType:"json",
					success:function(data){
						if(undefined != data && data.stat == 200){
							Public.tips({type: 3, content : '删除成功!'});
							showMode.refresh();
						}else{
							Public.tips({type: 1, content : data.message});
						}
					}
				});
			});
	   }else{
		   Public.tips({type: 1, content : '请选择数据!'});
	   }	
    },
    temp_clear:function(){
    	$.dialog.confirm('数据删除后无法恢复，确定要清除吗？', function(){
			$.ajax({
				type:"POST",
				url:config.BASEPATH+'shop/want/temp_clear/'+wt_type,
				data:{},
				cache:false,
				dataType:"json",
				success:function(data){
					if(undefined != data && data.stat == 200){
						Public.tips({type: 3, content : '删除成功!'});
						$("#grid").clearGridData();
						THISPAGE.gridTotal();
						$("#sumGrid").clearGridData();
						THISPAGE.sumGridTotal();
						if($("#CurrentMode").val() == '1'){
							showMode.refresh();
						}else{
							needSizeRefresh = true;
						}
					}else{
						Public.tips({type: 1, content : data.message});
					}
				}
			});
		});
    },
	save:function(isdraft){
		if (!$("#form1").valid()) {
			return;
		}
		var ids = $("#grid").jqGrid('getDataIDs');
		if (ids.length == 0){
			Public.tips({type: 2, content : '单据明细不存在，请选择货号！'});
			return;
		}
		$("#wt_isdraft").val(isdraft);
		$("#btn-save").attr("disabled",true);
		var saveUrl = config.BASEPATH+"shop/want/save";
		if($("#wt_id").val() != undefined){
			saveUrl = config.BASEPATH+"shop/want/update";
		}
		$.ajax({
			type:"POST",
			url:saveUrl,
			data:$('#form1').serialize(),
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					Public.tips({type: 3, content : '保存成功'});
					handle.loadData(data.data);
					setTimeout("api.zindex()",500);
				}else{
					Public.tips({type: 1, content : data.message});
					setTimeout("api.zindex()",500);
				}
				$("#btn-save").attr("disabled",false);
			}
		});
	},
	loadData:function(data){
		var pdata = {};
		pdata.id=data.wt_id;
		if(callback && typeof callback == 'function'){
			callback(pdata,oper,window);
		}
	},
	operFmatter :function(val, opt, row){
		var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
		html_con += '<i class="iconfont i-hand ui-icon-pencil" title="修改">&#xe60c;</i>';
		html_con += '<i class="iconfont i-hand ui-icon-trash" title="删除">&#xe60e;</i>';
		html_con += '<i class="iconfont i-hand ui-icon-image" title="图片">&#xe654;</i>';
		html_con += '</div>';
		return html_con;
	}
};

var THISPAGE = {
	init:function (){
		this.initDom();
		this.addEvent();
		this.initGrid();
		this.initEvent();
	},
	initDom:function(){
		$("#wt_date").val(config.TODAY);
		this.initProperty();
		needListRefresh = false;//列表模式
        needSizeRefresh = true;//尺码模式
        needSumRefresh = true;//汇总模式
        this.selectRow={};
	},
	initProperty:function(){
		$.ajax({
			type:"POST",
			url:config.BASEPATH+"base/dict/list?dtl_upcode=KEY_BILL",
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.data != "" && data.data.length > 0){
					$('#span_property').combo({
						value : 'dtl_code',
						text : 'dtl_name',
						width : 155,
						listHeight : 300,
						listId : '',
						defaultSelected : 0,
						editable : false,
						callback : {
							onChange : function(data) {
								$("#wt_property").val(data.dtl_name);
							}
						}
					}).getCombo().loadData(data.data,["dtl_name",$("#wt_property").val(),0]);
				}
			}
		 });
	},
	gridTotal:function(){
    	var grid=$('#grid');
		var wtl_applyamount=grid.getCol('wtl_applyamount',false,'sum');
    	var wtl_unitmoney=grid.getCol('wtl_unitmoney',false,'sum');
    	var wtl_costmoney=grid.getCol('wtl_costmoney',false,'sum');
    	var wtl_retailmoney=grid.getCol('wtl_retailmoney',false,'sum');
    	var wtl_rebatemoney=grid.getCol('wtl_rebatemoney',false,'sum');
    	grid.footerData('set',{wtl_applyamount:wtl_applyamount,wtl_unitmoney:wtl_unitmoney,wtl_costmoney:wtl_costmoney,wtl_retailmoney:wtl_retailmoney,wtl_rebatemoney:wtl_rebatemoney});
    	$("#wt_amount").val(wtl_applyamount);
    	$("#wt_money").val(PriceLimit.formatByBatch(wtl_unitmoney));
    	$("#wt_rebatemoney").val(PriceLimit.formatByBatch(wtl_rebatemoney));
    },
    sumGridTotal:function(){
    	var grid=$('#sumGrid');
    	var wtl_applyamount=grid.getCol('wtl_applyamount',false,'sum');
    	var wtl_unitmoney=grid.getCol('wtl_unitmoney',false,'sum');
    	var wtl_costmoney=grid.getCol('wtl_costmoney',false,'sum');
    	var wtl_retailmoney=grid.getCol('wtl_retailmoney',false,'sum');
    	var wtl_rebatemoney=grid.getCol('wtl_rebatemoney',false,'sum');
    	grid.footerData('set',{wtl_applyamount:wtl_applyamount,wtl_unitmoney:wtl_unitmoney,wtl_costmoney:wtl_costmoney,wtl_retailmoney:wtl_retailmoney,wtl_rebatemoney:wtl_rebatemoney});
    	$("#wt_amount").val(wtl_applyamount);
    	$("#wt_money").val(PriceLimit.formatByBatch(wtl_unitmoney));
    	$("#wt_rebatemoney").val(PriceLimit.formatByBatch(wtl_rebatemoney));
    },
	initGrid:function(){
		var self=this;
		var colModel = [
		    {label:'操作',name:'operate', width: 70, fixed:true, formatter: handle.operFmatter, sortable:false,align:'center'},
		    {label:'',name: 'wtl_pd_code', index: 'wtl_pd_code', hidden:true},
	    	{label:'商品货号',name: 'pd_no', index: 'pd_no', width: 100},
	    	{label:'商品名称',name: 'pd_name', index: 'pd_name', width: 100},
	    	{label:'颜色',name: 'cr_name', index: 'cr_name', width: 60},
	    	{label:'尺码',name: 'sz_name', index: 'sz_name', width: 60},
	    	{label:'杯型',name: 'br_name', index: 'br_name', width: 60},
	    	{label:'单位',name: 'pd_unit', index: 'pd_unit', width: 60},
	    	{label:'数量',name: 'wtl_applyamount', index: 'wtl_applyamount', width: 70,align:'right',sorttype: 'int',editable:true},
	    	{label:'零售价',name: 'wtl_unitprice', index: 'wtl_unitprice', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatBySell,editable:PriceLimit.hasSell()},
	    	{label:'零售金额',name: 'wtl_unitmoney', index: 'wtl_unitmoney', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatBySell},
	    	{label:'成本价',name: 'wtl_costprice', index: 'wtl_costprice', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'成本金额',name: 'wtl_costmoney', index: 'wtl_costmoney', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'备注',name: 'wtl_remark', index: 'wtl_remark', width: 180,editable:true}
	    ];
		$('#grid').jqGrid({
			url:queryurl,
			loadonce:true,
			datatype: 'json',
			width: _width,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:false,
			page:1,
			pgtext:false,
			recordtext:'共 {2} 条', 
			multiselect:false,//多选
			viewrecords: true,
			rowNum:9999,//每页条数
			cmTemplate: {sortable:true,title:true},
			shrinkToFit:false,//表格是否自动填充
			cellEdit: true,
            cellsubmit: 'clientArray',
            footerrow: true,
			jsonReader: {
				root: 'data', 
				repeatitems : false,
				id: 'wtl_id'  //图标ID
			},
			loadComplete: function(data){
				var ids = $("#grid").getDataIDs();
				THISPAGE.gridTotal();
			},
			loadError: function(xhr, status, error){		
			},
			ondblClickRow:function(rowid,iRow,iCol,e){
				handle.temp_update(rowid, '0');
			},
			formatCell:function (rowid, cellname, value, iRow, iCol){
            	self.selectRow.value=value;
				return value;
			},
			beforeSaveCell :function(rowid, cellname, value, iRow, iCol){
				if (cellname == 'wtl_applyamount' && self.selectRow.value != value){
					if(value == '' || isNaN(value) || parseInt(value) <= 0){
						return self.selectRow.value;
					} 
					if(parseInt(self.selectRow.value) == parseInt(value)){
						return self.selectRow.value;
					}
					if(parseFloat(value).toFixed(0).length > 9|| parseInt(value) >1e+9){
						return self.selectRow.value;
					}
					handle.temp_updateAmount(rowid, parseInt(value));
					return parseInt(value);
				}else if(cellname == 'wtl_unitprice' && self.selectRow.value != value){
					if(value == '' || isNaN(value) || parseFloat(value) < 0){
						return self.selectRow.value;
					}
					if(parseFloat(self.selectRow.value) == parseFloat(value)){
						return self.selectRow.value;
					}
					if(parseFloat(value).toFixed(2).length > 11 || parseFloat(value) >1e+11){
						return self.selectRow.value;
					}
					var rowData = $("#grid").jqGrid("getRowData", rowid);
					if(cellname == 'wtl_unitprice'){
						handle.temp_updatePrice(rowData.wtl_pd_code, parseFloat(value).toFixed(2));
					}
					return parseFloat(value).toFixed(2);
				}else if(cellname == 'wtl_remark' && self.selectRow.value != value){
					handle.temp_updateRemarkById(rowid, value);
				}
				
				return value;
			},
			afterSaveCell:function(rowid, cellname, value, iRow, iCol){
				if (cellname == 'wtl_applyamount' && self.selectRow.value != value){
					var rowData = $("#grid").jqGrid("getRowData", rowid);
					rowData.wtl_unitmoney = rowData.wtl_applyamount * rowData.wtl_unitprice;
					rowData.wtl_costmoney = rowData.wtl_applyamount * rowData.wtl_costprice;
					$("#grid").jqGrid('setRowData', rowid, rowData);
					THISPAGE.gridTotal();
				}
				
			}
	    });
	},
	initSumGrid:function(){
		var self=this;
		var colModel = [
		    {label:'操作',name:'operate', width: 70, fixed:true, formatter: handle.operFmatter, sortable:false,align:'center'},
	    	{label:'',name: 'wtl_pd_code', index: 'wtl_pd_code', hidden:true},
	    	{label:'商品货号',name: 'pd_no', index: 'pd_no', width: 100},
	    	{label:'商品名称',name: 'pd_name', index: 'pd_name', width: 100},
	    	{label:'品牌',name: 'bd_name', index: 'pd_bd_code', width: 80},
	    	{label:'类别',name: 'tp_name', index: 'pd_tp_code', width: 80},
	    	{label:'单位',name: 'pd_unit', index: 'pd_unit', width: 60},
	    	{label:'数量',name: 'wtl_applyamount', index: 'wtl_applyamount', width: 70,align:'right',sorttype: 'int'},
	    	{label:'零售价',name: 'wtl_unitprice', index: 'wtl_unitprice', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatBySell,editable:PriceLimit.hasSell()},
	    	{label:'零售金额',name: 'wtl_unitmoney', index: 'wtl_unitmoney', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatBySell},
	    	{label:'成本价',name: 'wtl_costprice', index: 'wtl_costprice', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'成本金额',name: 'wtl_costmoney', index: 'wtl_costmoney', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'备注',name: 'wtl_remark', index: 'wtl_remark', width: 180,editable:true}
	    ];
		$('#sumGrid').jqGrid({
			url:querysumurl,
			loadonce:true,
			datatype: 'json',
			width: _width,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#sumPage',//分页
			pgbuttons:false,
			page:1,
			pgtext:false,
			recordtext:'共 {2} 条', 
			multiselect:false,//多选
			viewrecords: true,
			rowNum:9999,//每页条数
			cmTemplate: {sortable:true,title:true},
			shrinkToFit:false,//表格是否自动填充
			cellEdit: true,
            cellsubmit: 'clientArray',
            footerrow: true,
			jsonReader: {
				root: 'data', 
				repeatitems : false,
				id: 'wtl_id'  //图标ID
			},
			loadComplete: function(data){
				THISPAGE.sumGridTotal();
			},
			loadError: function(xhr, status, error){		
			},
			ondblClickRow:function(rowid,iRow,iCol,e){
				handle.temp_update(rowid, '2');
			},
			formatCell:function (rowid, cellname, value, iRow, iCol){
            	self.selectRow.value=value;
				return value;
			},
			beforeSaveCell :function(rowid, cellname, value, iRow, iCol){
				if(cellname == 'wtl_unitprice' && self.selectRow.value != value){
					if(value == '' || isNaN(value) || parseFloat(value) < 0){
						return self.selectRow.value;
					}
					if(parseFloat(self.selectRow.value) == parseFloat(value)){
						return self.selectRow.value;
					}
					if(parseFloat(value).toFixed(2).length > 11 || parseFloat(value) >1e+11){
						return self.selectRow.value;
					}
					var rowData = $("#sumGrid").jqGrid("getRowData", rowid);
					if(cellname == 'wtl_unitprice'){
						handle.temp_updatePrice(rowData.wtl_pd_code, parseFloat(value).toFixed(2));
					}
					return parseFloat(value).toFixed(2);
				}else if(cellname == 'wtl_remark' && self.selectRow.value != value){
					var rowData = $("#sumGrid").jqGrid("getRowData", rowid);
					handle.temp_updateRemarkByPdCode(rowData.wtl_pd_code, value);
				}
				return value;
			},
			afterSaveCell:function(rowid, cellname, value, iRow, iCol){
				
			}
	    });
	},
	initSizeGroupGrid:function(dyColNames, sizeCodeMap) {
		var self=this;
        var headers = [];
        var dyns = dyColNames;
        var dySize = dyns.length;
        var dms = [];
        for (var i = 0; i < dyns.length; i++) {
            var dys = dyns[i];
            for (var j = 0; j < dys.length; j++) {
                var dyss = null;
                dyss = dys[j].split('_AND_');
                if (i == 0 && j == 0) {
                    dyns[i][j] = dyss[0];
                }
                headers.push(dyss[1]);
                dms.push({label:dyss[1],name: dyss[0], index: dyss[0], width: 45, title: false, align: 'right', sorttype: 'int', sortable: false});
            }
            break;
        }
		var colModel = [
            {label:'',name: 'sizeGroupCode', hidden: true},
            {label:'',name: 'pd_code', index: 'pd_code', width: 100,hidden:true},
            {label:'',name: 'cr_code', index: 'cr_code', width: 100,hidden:true},
            {label:'',name: 'br_code', index: 'br_code', width: 100,hidden:true},
            {label:'操作',name:'operate', width: 70, fixed:true, formatter: handle.operFmatter, sortable:false,align:'center'},
            {label:'商品货号',name: 'pd_no', index: 'pd_no', width: 100},
	    	{label:'商品名称',name: 'pd_name', index: 'pd_name', width: 100},
	    	{label:'颜色',name: 'cr_name', index: 'wtl_cr_code', width: 80},
	    	{label:'杯型',name: 'br_name', index: 'wtl_br_code', width: 80},
        ];
        colModel = colModel.concat(dms);
        colModel = colModel.concat([
            {label:'数量',name: 'Amount_Total',	index:'Amount_Total',	width: 70, align: 'right', sorttype: 'int', sortable: false},
            {label:'零售价',name: 'unit_price', index: 'unit_price', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatBySell,editable:PriceLimit.hasSell()},
	    	{label:'零售金额',name: 'unit_money', index: 'unit_money', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatBySell},
	    	{label:'成本价',name: 'cost_price', index: 'cost_price', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'成本金额',name: 'cost_money', index: 'cost_money', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost}
	    ]);
        $('#sizeGrid').jqGrid({
			url: querysizeurl,
			loadonce:true,
            datatype: 'json',
            autowidth: true,
			height: _height,
            gridview: true,
            colModel: colModel,
            rownumbers: true,//行号
            pager: '#sizePage',//分页
            pgbuttons:false,
			page:1,
			pgtext:false,
			recordtext:'共 {2} 条', 
            viewrecords: true,
            rowNum: 9999,//每页条数
            shrinkToFit: false,//表格是否自动填充
            cellEdit: true,
            cellsubmit: 'clientArray',
            footerrow: true,
            userDataOnFooter: true,
			jsonReader: {
				root: 'data.data',
				userdata: 'data.userData',
				repeatitems : false,
				id:'id'
			},
			loadComplete: function(data) {
				
			},
			gridComplete:function(){
				Public.resizeSpecifyGrid('sizeGrid', 290 + (dyns.length * 32),2);
			},
			loadError: function(xhr, status, error) {
                Public.tips({type: 1, content : '操作失败了哦，服务可能已过期，请按F5刷新！'});
			},
			ondblClickRow:function(rowid,iRow,iCol,e){
				handle.temp_update(rowid, '1');
			},
			formatCell:function (rowid, cellname, value, iRow, iCol){
            	self.selectRow.value=value;
				return value;
			},
			beforeSaveCell :function(rowid, cellname, value, iRow, iCol){
				if(cellname == 'unit_price' && self.selectRow.value != value){
					if(value == '' || isNaN(value) || parseFloat(value) < 0){
						return self.selectRow.value;
					}
					if(parseFloat(self.selectRow.value) == parseFloat(value)){
						return self.selectRow.value;
					}
					if(parseFloat(value).toFixed(2).length > 11 || parseFloat(value) >1e+11){
						return self.selectRow.value;
					}
					var rowData = $("#sizeGrid").jqGrid("getRowData", rowid);
					if(cellname == 'unit_price'){
						handle.temp_updatePrice(rowData.pd_code, parseFloat(value).toFixed(2));
					}
					return parseFloat(value).toFixed(2);
				}
				return value;
			},
			afterSaveCell:function(rowid, cellname, value, iRow, iCol){
				
			},
			onPaging: function(pgButton) {
				
			},
            onSelectRow: function (rowId, status) {
                var sizeG = $("#sizeGrid").jqGrid("getRowData", rowId).sizeGroupCode;
                var bg = $('[sizeGCode=' + sizeG + ']').css("background");
                if (bg == 'none') {
                    return;
                }
                $("[sizeGCode]").css("background-color", '#eee');
                $('[sizeGCode=' + sizeG + ']').css({ "background": "none", "background-color": "#F8FF94"});
            }
	    });
        if (dySize >= 2) {
        	$('#sizeGrid').jqGrid('setGroupHeaders', {
                useColSpanStyle: true,
                groupHeaders:[]
            });
            $('#sizeGrid').jqGrid("setComplexGroupHeaders", {
                complexGroupHeaders: {startColumnName: dyns[0][0], numberOfColumns: dyns[0].length},
                rowspan: dySize,
                topTitle:true
            });
            for (var key in sizeCodeMap) {
                $('#sizeGrid').jqGrid("setComplexGroupHeaders",{
                    complexGroupHeaders: {startColumnName: dyns[0][0], numberOfColumns: dyns[0].length},
                    rowspan: dySize,
                    sizeGroupCode: key,
                    titleTextGroup:sizeCodeMap[key],
                    topTitle:false
                });
            }
        }else{
        	$('#sizeGrid').jqGrid('setGroupHeaders', {
                useColSpanStyle: true,
                groupHeaders: [{startColumnName: dyns[0][0], numberOfColumns: dyns[0].length, titleText: '尺码'}]
            });
        }
    },
	reloadGridData: function () {
        $("#grid").jqGrid('setGridParam', {datatype: 'json', page: 1, url: queryurl}).trigger("reloadGrid");
    },
	initEvent:function(){
		$('#btn-import').on('click', function(e){
			e.preventDefault();
			Choose.doImport();
		});
		$('#btn-copy').on('click', function(e){
			e.preventDefault();
			Choose.copy();
		});
		$('#btn-save').on('click', function(e){
			e.preventDefault();
			handle.save(0);
		});
		$("#btn_close").click(function(e){
			e.preventDefault();
			api.close();
		});
		//清除
        $('#btnClear').click(function(e){
        	e.preventDefault();
        	handle.temp_clear();
		});
        //修改-列表模式
        $('#grid').on('click', '.operating .ui-icon-pencil', function (e) {
        	e.preventDefault();
        	var id = $(this).parent().data('id');
        	handle.temp_update(id, '0');
        });
        
        //删除-列表模式
		$('#grid').on('click', '.operating .ui-icon-trash', function(e) {
			e.preventDefault();
			var id = $(this).parent().data('id');
			handle.temp_del(id);
		});
		
		$('#grid').on('click', '.operating .ui-icon-image', function (e) {
        	e.preventDefault();
        	var id = $(this).parent().data('id');
        	viewProductImg($("#grid").jqGrid("getRowData", id).wtl_pd_code);
        });
	},
	addEvent:function(){
		//移除事件，防止重复绑定
		$('#sumGrid').off('click','.operating .ui-icon-pencil');
		$('#sumGrid').off('click','.operating .ui-icon-trash');
		$('#sumGrid').off('click','.operating .ui-icon-image');
		$('#sizeGrid').off('click','.operating .ui-icon-pencil');
		$('#sizeGrid').off('click','.operating .ui-icon-trash');
		$('#sizeGrid').off('click','.operating .ui-icon-image');
        //修改-尺码模式
        $('#sizeGrid').on('click', '.operating .ui-icon-pencil', function (e) {
        	e.preventDefault();
        	var id = $(this).parent().data('id');
			handle.temp_update(id, '1');
        });
        //修改-汇总模式
        $('#sumGrid').on('click', '.operating .ui-icon-pencil', function (e) {
        	e.preventDefault();
        	var id = $(this).parent().data('id');
			handle.temp_update(id, '2');
        });
		
		 //删除-汇总模式
		$('#sumGrid').on('click', '.operating .ui-icon-trash', function(e) {
			e.preventDefault();
			var id = $(this).parent().data('id');
			handle.temp_delByPiCode(id, '2');
		});
		//删除-尺码模式
		$('#sizeGrid').on('click', '.operating .ui-icon-trash',function(e) {
			e.preventDefault();
			var id = $(this).parent().data('id');
			handle.temp_delByPiCode(id, '1');
		});
		
		$('#sizeGrid').on('click', '.operating .ui-icon-image', function (e) {
        	e.preventDefault();
        	var id = $(this).parent().data('id');
        	viewProductImg($("#sizeGrid").jqGrid("getRowData", id).pd_code);
        });
        $('#sumGrid').on('click', '.operating .ui-icon-image', function (e) {
        	e.preventDefault();
        	var id = $(this).parent().data('id');
        	viewProductImg($("#sumGrid").jqGrid("getRowData", id).wtl_pd_code);
        });
	}
};

THISPAGE.init();